import { login, logout, reqUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { constantRoutes, allAsyncRoutes, anyRoute } from "@/router/routes"
import { cloneDeep } from 'lodash'


function getAsyncRoutes(
  routes,
  userRoutes
) {
  const menuRoutes = [];

  routes.forEach((r) => {
    if (userRoutes.includes(r.name)) {
      if (Array.isArray(r.children)) {
        r.children = getAsyncRoutes(r.children, userRoutes);
      }
      menuRoutes.push(r);
    }
  });

  return menuRoutes;
}

const getDefaultState = () => {
  return {
    token: getToken() || '',
    name: '',
    avatar: '',
    menuRoutes: [],
    routes: [],
    buttons: [],
    roles: [],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
}

const actions = {



  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    try {
      const res = await login({ username: username.trim(), password: password })

      commit("SET_TOKEN", res.data.token)
      setToken(res.data.token)
    } catch (e) {
      console.log('请求错误');

    }
  },
  async getUserInfo({ state, commit }) {

    try {
      const res = await reqUserInfo()
      const { name, avatar, routes, buttons, roles } = res.data
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      commit('SET_ROUTES', routes)
      commit('SET_BUTTONS', buttons)
      commit('SET_ROLES', roles)
      const userRoutes = getAsyncRoutes(cloneDeep(allAsyncRoutes), state.routes);
      state.menuRoutes.push(...constantRoutes, ...userRoutes);
      router.addRoutes(userRoutes)

      router.addRoutes(anyRoute)
    } catch (e) {
      this.resetToken();
      return Promise.reject(e)
    }


  },

  /* 退出 */
  async logout({ commit, state }) {
    try {
      await logout();
      removeToken();
      resetRouter();
      commit('RESET_STATE')
    } catch (e) {
      this.Promise.reject(e);
    }
  },
  resetToken({ commit }) {
    try {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
    } catch (e) {
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

